package com.hup.utils.swing.customView;

import com.hup.utils.commons.TextUtil;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

/**
 * 实现hint提示效果
 * <pre>
 *     需要重写paint
 *    public void paint(Graphics g) {
 *    //paint.st -> paintComponent.st,ed -> paint.st
 *    super.paint(g);
 *    paintHint(this, g);
 *    }
 * </>
 *
 * @author hugan
 * @date 2019/9/8
 */
public interface BaseHintText {

    /**
     * 构造时调用
     */
    default void initHintListener() {
        ((JTextComponent) this).addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                ((JComponent) e.getSource()).repaint();
            }

            @Override
            public void focusLost(FocusEvent e) {
                ((JComponent) e.getSource()).repaint();
            }
        });
    }

    default String getHint() {
        return ((JTextComponent) this).getToolTipText();
    }

    /**
     * 重写paint(g)方法,末尾调用
     * @param c 当前控件
     * @param g paint(Graphics g)中的g
     */
    default void paintHint(JTextComponent c, Graphics g) {
        String text = c.getText();
        String toolTipText = getHint();
        if (!TextUtil.isBlank(text) || TextUtil.isBlank(toolTipText)) {
            //log.info("not hint");
            return;
        }
        //g不能在这里get出来,否则在移动或调整大小后,图像会消失
        g.setColor(Color.LIGHT_GRAY);
        int fontHeight = c.getFontMetrics(c.getFont()).getHeight();
        Insets insets = c.getInsets();
        int x = insets.left;
        g.drawString(toolTipText, x, fontHeight);
    }

}
